package com.registtools.util;


import org.apache.commons.codec.binary.Base64;
import org.apache.http.Consts;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


/**
 * @program: complaint
 * @description: 知音楼机器人发送通知
 **/

public class YachNoticeUtil {

    private static final Logger logger = LoggerFactory.getLogger(YachNoticeUtil.class);
    /**
     * 消息类型
     */
    public enum type {
        ERROR("ERROR"),
        WARN("WARN"),
        NOTICE("NOTICE"),
        MONITOR("MONITOR")
        ;

        private String code;

        type(String code) {
            this.code = code;
        }

        public String getCode() {
            return code;
        }
    }
    //机器人配置秘钥,由外部传入
//    private static String secret = "SECf754efb9d848c24454bfae2838cc64a6";

    /**
     *
     * @param paramsMap
     * @param yachUrl
     * @param secret
     */
    public static void sendMsg(Map<String, Object> paramsMap, String yachUrl,String secret) {
        logger.info("======sendYachMsg start");
        // 发送钉钉机器人群组消息
        try {
            String content = JsonUtil.mapToJson(paramsMap);
            logger.info("======sendYachMsg content={}", content);
            Long timestamp = System.currentTimeMillis();
            String yachUrl1 = yachUrl + "&timestamp=" + timestamp + "&sign=" + sign(timestamp,secret);
            String json = Request.Post(yachUrl1)
                    .connectTimeout(2000)
                    .socketTimeout(2000)
                    .bodyString(content, ContentType.APPLICATION_JSON)
                    .execute().returnContent().asString(Consts.UTF_8);
            logger.info(json);
        } catch (Exception e) {
            logger.error("======addExecuteLog push yach msg error:{}", e.getMessage());
        }
        logger.info("======sendYachMsg end");
    }

    /***
     * 外部调用，发送内容
     * @param content：发送内容
     * @param yachUrl：机器人地址=>来源群机器人配置
     * @param secret：机器人秘钥=>来源群机器人配置
     */
    public static void sendMsgText(String content, String yachUrl,String secret) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("msgtype", "text");
        Map<String, Object> textMap = new HashMap<>();
        textMap.put("content",  ":" + content + " ");
        paramsMap.put("text", textMap);
        Map<String, Object> atMap = new HashMap<>();
        atMap.put("isAtAll", true);
        paramsMap.put("at", atMap);
        sendMsg(paramsMap, yachUrl,secret);
    }
    /**
     * 获取签名
     * @return
     * @throws Exception
     */
    private static String sign(Long timestamp,String secret) throws Exception {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
    }


}
